package net.huashitong.synthetical.newSupervision.controller;

import com.sirdc.modules.core.exceptions.SystemException;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysLoginFilter;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.*;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.synthetical.newSupervision.entity.*;
import net.huashitong.synthetical.newSupervision.filter.TaskMessageFilter;
import net.huashitong.synthetical.newSupervision.filter.TaskNewFilter;
import net.huashitong.synthetical.newSupervision.filter.UnitPersonnelFilter;
import net.huashitong.synthetical.newSupervision.service.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/7/2
 * Time: 20:39
 * To change this template use File | Settings | File Templates.
 * Description:
 */
@Controller
@RequestMapping("/project")
public class TaskController extends JsonBaseController {

    @Autowired
    private TaskSendService taskSendService;

    @Autowired
    private TaskNewService taskNewService;

    @Autowired
    private TaskLogService taskLogService;

    @Autowired
    private TaskWorkableService taskWorkableService;

    @Autowired
    private SysUserPermissionService sysUserPermissionService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private DeptService deptService;

    @Autowired
    private UnitPersonnelService unitPersonnelService;

    @Autowired
    private TaskCopeToService taskCopeToService;

    @Autowired
    private TaskMessageService taskMessageService;

    @Autowired
    private TaskBackService taskBackService;

    @Override
    protected String getView(String s) {
        return "/modules/project/task/" + s;
    }

    @RequestMapping("/filter")
    public String filter() {
        return getView("filter");
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage(Model model) {
        SysUser user = sysUserService.getById(SysUserUtils.getUserId());
        model.addAttribute("user",user );
        return getView("query");
    }

    /**
     * 根据不同的用户信息展示各自联的项目
     *
     * @param taskNewFilter
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid taskByUser(TaskNewFilter taskNewFilter) {
        String userId = SysUserUtils.getUserId();
        SysLogin login = sysLoginService.getById(userId);
        String deptId = login.getDeptId();
        SysDept dept = sysDeptService.getById(deptId);
        List<TaskNew> projectList = new ArrayList<>();
        if ("01".equals(login.getRoleId())) {
            taskNewFilter.setInspectionId(deptId);
            projectList = taskNewService.getProjectList(taskNewFilter);
        } else {
            taskNewFilter.setOperatorId(userId);
            projectList = taskNewService.getProjectList(taskNewFilter);
        }
        if ("admin".equals(login.getUsername())) {
            projectList = taskNewService.query();
        }
        //如果是县主管
        if ("20190802100000000091".equals(deptId)) {
            taskNewFilter.setCountyLeaderId(userId);
            projectList = taskCopeToService.queryFilter(taskNewFilter);
        }
        return coverJqGrid(taskNewFilter, projectList);
    }

    /**
     * 返回新增页面
     *
     * @param model
     * @return url
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String showAddView(TaskNew taskNew, Model model) {
        return getView("form");
    }

    /**
     * 任务立项
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Message create(@ModelAttribute TaskNewFilter filter) {
        taskNewService.saveProject(filter);
        return coverMessage("200");
    }

    /**
     * 修改任务
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public Message update(@ModelAttribute TaskNewFilter filter) {
        taskNewService.updateTask(filter);
        return coverMessage("200");
    }

    /**
     * 根据部门id查询用户
     * 用于取出督查经办人,
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "queryByDeptId", method = RequestMethod.POST)
    public List<SysUser> queryByDeptId() {
        String userId = SysUserUtils.getUserId();
        SysLogin login = sysLoginService.getById(userId);
        String deptId = login.getDeptId();
        SysUserFilter filter = new SysUserFilter();
        filter.setDeptId(deptId);
        filter.setRoleId("02");
        List<SysUser> userList = new ArrayList<>();
        List<String> userIds = sysLoginService.queryLoginByRoleDept(filter);
        for (String id : userIds) {
            SysUser user = sysUserService.getById(id);
            userList.add(user);
        }
        return userList;
    }


    /**
     * 查询当前单位人员
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryUnitPersonnel", method = RequestMethod.POST)
    public List<UnitPersonnel> queryUnitPersonnel() {
        String deptId = SysUserUtils.getDeptId();
        UnitPersonnelFilter filter = new UnitPersonnelFilter();
        filter.setDeptId(deptId);
        return unitPersonnelService.queryFilter(filter);
    }

    /**
     * 返回所有乡镇单位列表,以及单位管理员userid;
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deptList", method = RequestMethod.POST)
    public List<Map<String, String>> deptList() {
        List<SysDept> list = deptService.queryDeptList("/02/");
        List<Map<String, String>> mapList = new ArrayList<>();
        Map<String, String> map = null;
        for (SysDept sysDept : list) {
            String deptName = sysDept.getDeptName();
            String deptRelation = sysDept.getDeptRelation() + sysDept.getDeptId() + "/";
            String deptId = sysDept.getSysId();
            map = new HashMap<>();
            map.put("deptName", deptName);
            map.put("deptId", deptId);
            map.put("deptRelation", deptRelation);
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 根据县领导单位id取出所有用户
     *
     * @param deptId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/leaderList", method = RequestMethod.POST)
    public List<Map<String, String>> leaderList(String deptId) {
        SysUserFilter filter = new SysUserFilter();
        filter.setDeptId(deptId);
        List<SysLogin> list = sysLoginService.queryUserLoginByRoleDept(filter);
        List<Map<String, String>> mapList = new ArrayList<>();

        for (SysLogin sysLogin : list) {
            Map<String, String> map = new HashMap<>();
            SysUser user = sysUserService.getById(sysLogin.getSysId());
            map.put("userName", user.getName());
            map.put("userId", sysLogin.getSysId());
            mapList.add(map);
        }
        return mapList;
    }

    /**
     * 返回最后一级单位列表,以及单位管理员userId;
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/childDeptList", method = RequestMethod.POST)
    public List<Map<String, String>> childDeptList(String deptRelation) {
        List<SysDept> deptList = deptService.queryDeptList(deptRelation);
        List<Map<String, String>> list = new ArrayList<>();
        for (SysDept dept : deptList) {
            Map<String, String> map = new HashMap<>();
            String deptName = dept.getDeptName();
            String sysId = dept.getSysId();
            SysUserFilter sysUserFilter = new SysUserFilter();
            sysUserFilter.setDeptId(sysId);
            sysUserFilter.setRoleId("01");
            List<SysLogin> sysLoginList = sysLoginService.queryUserLoginByRoleDept(sysUserFilter);
            if (sysLoginList.size() > 0) {
                map.put("deptName", deptName);
                map.put("userId", sysLoginList.get(0).getSysId());
                list.add(map);
            }
        }
        return list;
    }


    /**
     * 删除项目
     *
     * @param id
     */
    @ResponseBody
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public Message delete(@PathVariable List<String> id) {
        taskNewService.deleteTask(id);
        return coverMessage("200");
    }

    /**
     * 查看详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public String detail(Model model, @PathVariable String id) {
        TaskNew task = taskNewService.getById(id);
        List<TaskSend> sendList = taskSendService.queryByTaskId(id);
        List<TaskWorkable> workableList = taskWorkableService.queryByTaskId(id);
        //抄送人
        List<SysUser> copeToList=new ArrayList<>();
        List<TaskCopeTo> copeTos = taskCopeToService.getByTaskId(id);
        for (TaskCopeTo copeTo : copeTos) {
            SysUser user = sysUserService.getById(copeTo.getCountyLeaderId());
            copeToList.add(user);
        }
        model.addAttribute("taskNew", task);
        model.addAttribute("copeToList", copeToList);//任务抄送人集合
        model.addAttribute("sendList", sendList);
        model.addAttribute("workableList", workableList);
        return getView("detail");
    }


    /**
     * 查看任务流程
     *
     * @return
     */
    @RequestMapping(value = "/flow/{id}", method = RequestMethod.GET)
    public String test(Model model, @PathVariable String id) {
        List<TaskLog> logList = taskLogService.queryByTableId(id);
        model.addAttribute("logList", logList);
        return getView("flow");
    }

    /*  *//**
     * 办结评价页面
     *
     * @param id
     * @return
     *//*
    @RequestMapping(value = "/comment/{id}", method = RequestMethod.GET)
    public String comment(Model model, @PathVariable String id) {
        TaskNew task = taskNewService.getById(id);
        List<TaskSend> sendList = taskSendService.queryByTaskId(id);
        List<TaskWorkable> workableList = taskWorkableService.queryByTaskId(id);
        model.addAttribute("taskNew", task);
        model.addAttribute("sendList", sendList);
        model.addAttribute("workableList", workableList);
        return getView("comment");
    }*/

    /*  *//**
     * 办结评价
     *
     * @param filter
     * @return
     *//*
    @ResponseBody
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    public Message comment(@ModelAttribute TaskNewFilter filter) {
        taskNewService.updateComment(filter);
        return coverMessage("200");
    }
*/

    /**
     * 导出督查任务情况一览表
     *
     * @param filter
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/exportTaskNew", method = RequestMethod.GET)
    public void exportTaskNew(@ModelAttribute TaskNewFilter filter, HttpServletResponse response) {
        HSSFWorkbook taskExcel = taskNewService.getTaskExcel(filter);
        HSSFSheet sheet = taskExcel.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();
        if (rowNum == 0) {
            throw new SystemException("没有数据");
        }

        OutputStream out = null;
        try {
            out = response.getOutputStream();

            String filename = "县政府会议纪要未办结事项督查情况一览表.xls";
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
            taskExcel.write(out);
        } catch (Exception e) {

        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}